<!doctype html>
<html lang="zh_cn" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>房东辅助系统</title>
    <link rel="stylesheet" type="text/css" href="../static/css/bootstrap.css">
    <script type="text/javascript" src="../static/js/jquery.min.js"></script>
    <script type="text/javascript" src="../static/js/bootstrap.bundle.js"></script>
</head>
<body>
    <div class="container px-0 vh-100 bg-dark-subtle">
        <div class="accordion p-0" id="buildingAccordion">
            <!-- 楼栋列表将通过 JavaScript 动态渲染 -->
        </div>
        <div class="btn-group fixed-bottom justify-content-center">
            <a href="/page/main.html" class="btn btn-primary rounded-0">首页</a>
            <a href="#" class="btn btn-primary active rounded-0">管理</a>
        </div>
    </div>

    <!-- 错误提示框 -->
    <div class="modal fade" id="errModal" tabindex="-1" aria-labelledby="modalLabErr" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabErr">错误提示</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-info text-center" id="err-body"></div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 修改楼栋 -->
    <div class="modal fade" id="editBuildingModal" tabindex="-1" aria-labelledby="modalLabEditBuilding" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabEditBuilding">修改楼栋</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-0">
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="editBuildingNameInput" class="col-form-label-sm">楼栋简称</label>
                        </div>
                        <div class="col-8">
                            <input type="text" class="form-control form-control-sm" id="editBuildingNameInput" aria-describedby="editBuildingNameBlock" placeholder="请输入楼栋简称" required />
                        </div>
                    </div>
                    <div class="row mx-1">
                        <div id="editBuildingNameBlock" class="form-text text-info small">
                            &nbsp;&nbsp;楼栋简称不能重复，长度10个字符以内。
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="editBuildingAddressInput" class="form-label small">楼栋地址</label>
                        </div>
                        <div class="col-8">
                            <input type="text" class="form-control form-control-sm" id="editBuildingAddressInput" aria-describedby="editBuildingAddressBlock" placeholder="请输入楼栋地址" required />
                        </div>
                    </div>
                    <div class="row mx-1">
                        <div id="editBuildingAddressBlock" class="form-text text-info small">
                            &nbsp;&nbsp;楼栋地址,长度30个字符以内。
                        </div>
                    </div>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-primary" id="saveEditBuildingBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除楼栋 -->
    <div class="modal fade" id="deleteBuildingModal" tabindex="-1" aria-labelledby="modalLabDeleteBuilding" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabDeleteBuilding">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <p class="mb-0" id="deleteBuildingMessage">确定要删除该楼栋吗？删除后无法恢复。</p>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-danger" id="confirmDeleteBuildingBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 修改房间 -->
    <div class="modal fade" id="editRoomModal" tabindex="-1" aria-labelledby="modalLabEditRoom" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabEditRoom">修改房间</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-0">
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="editRoomNameInput" class="col-form-label-sm">房间名</label>
                        </div>
                        <div class="col-8">
                            <input type="text" class="form-control form-control-sm" id="editRoomNameInput" placeholder="请输入房间名" required />
                        </div>
                    </div>
                    <div class="row mx-1">
                        <div id="editRoomNameBlock" class="form-text text-info small">
                            &nbsp;&nbsp;房间名长度10个字符以内。
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="editRoomWaterNumInput" class="form-label small">水表读数</label>
                        </div>
                        <div class="col-8">
                            <input type="number" class="form-control form-control-sm" id="editRoomWaterNumInput" placeholder="请输入水表读数" min="0" required />
                        </div>
                    </div>
                    <div class="row mx-1">
                        <div id="editRoomWaterNumBlock" class="form-text text-info small">
                            &nbsp;&nbsp;当前水表读数。
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="editRoomElectricNumInput" class="form-label small">电表读数</label>
                        </div>
                        <div class="col-8">
                            <input type="number" class="form-control form-control-sm" id="editRoomElectricNumInput" placeholder="请输入电表读数" min="0" required />
                        </div>
                    </div>
                    <div class="row mx-1">
                        <div id="editRoomElectricNumBlock" class="form-text text-info small">
                            &nbsp;&nbsp;当前电表读数。
                        </div>
                    </div>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-primary" id="saveEditRoomBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除房间 -->
    <div class="modal fade" id="deleteRoomModal" tabindex="-1" aria-labelledby="modalLabDeleteRoom" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabDeleteRoom">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <p class="mb-0" id="deleteRoomMessage">确定要删除该房间吗？删除后无法恢复。</p>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-danger" id="confirmDeleteRoomBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 入住合同 -->
    <div class="modal fade" id="addContractModal" tabindex="-1" aria-labelledby="modalLabAddContract" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabAddContract">入住登记</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-0">
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="contractStartDateInput" class="col-form-label-sm">开始日期</label>
                        </div>
                        <div class="col-8">
                            <input type="date" class="form-control form-control-sm" id="contractStartDateInput" required />
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="contractEndDateInput" class="col-form-label-sm">截止日期</label>
                        </div>
                        <div class="col-8">
                            <input type="date" class="form-control form-control-sm" id="contractEndDateInput" required />
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="contractPriceInput" class="col-form-label-sm">每月租金</label>
                        </div>
                        <div class="col-8">
                            <input type="number" class="form-control form-control-sm" id="contractPriceInput" placeholder="请输入每月租金" min="1" required />
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="contractLesseeInput" class="col-form-label-sm">承租人姓名</label>
                        </div>
                        <div class="col-8">
                            <input type="text" class="form-control form-control-sm" id="contractLesseeInput" placeholder="请输入承租人姓名" maxlength="30" required />
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="contractLesseeMobileInput" class="col-form-label-sm">手机号</label>
                        </div>
                        <div class="col-8">
                            <input type="tel" class="form-control form-control-sm" id="contractLesseeMobileInput" placeholder="请输入手机号" maxlength="11" required />
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="contractLesseeNoInput" class="col-form-label-sm">身份证号</label>
                        </div>
                        <div class="col-8">
                            <input type="text" class="form-control form-control-sm" id="contractLesseeNoInput" placeholder="请输入身份证号" maxlength="18" required />
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="contractDepositInput" class="col-form-label-sm">押金</label>
                        </div>
                        <div class="col-8">
                            <input type="number" class="form-control form-control-sm" id="contractDepositInput" placeholder="请输入押金" min="0" required />
                        </div>
                    </div>
                    <div class="row mx-1 mt-2">
                        <div class="col-4">
                            <label for="contractRemarkInput" class="col-form-label-sm">备注</label>
                        </div>
                        <div class="col-8">
                            <textarea class="form-control form-control-sm" id="contractRemarkInput" placeholder="请输入备注" maxlength="60" rows="2"></textarea>
                        </div>
                    </div>
                    <div class="row mx-1">
                        <div id="contractErrorBlock" class="form-text text-danger small"></div>
                    </div>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-primary" id="saveAddContractBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 查看租约 -->
    <div class="modal fade" id="viewContractModal" tabindex="-1" aria-labelledby="modalLabViewContract" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabViewContract">租约信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-2">
                    <div class="row mb-2">
                        <div class="col-4"><strong>开始日期：</strong></div>
                        <div class="col-8" id="viewContractStartDate"></div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4"><strong>截止日期：</strong></div>
                        <div class="col-8" id="viewContractEndDate"></div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4"><strong>每月租金：</strong></div>
                        <div class="col-8" id="viewContractPrice"></div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4"><strong>承租人姓名：</strong></div>
                        <div class="col-8" id="viewContractLessee"></div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4"><strong>手机号：</strong></div>
                        <div class="col-8" id="viewContractLesseeMobile"></div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4"><strong>身份证号：</strong></div>
                        <div class="col-8" id="viewContractLesseeNo"></div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4"><strong>押金：</strong></div>
                        <div class="col-8" id="viewContractDeposit"></div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4"><strong>备注：</strong></div>
                        <div class="col-8" id="viewContractRemark"></div>
                    </div>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认退房 -->
    <div class="modal fade" id="checkoutRoomModal" tabindex="-1" aria-labelledby="modalLabCheckoutRoom" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header p-2">
                    <h5 class="modal-title fs-6 fw-bolder" id="modalLabCheckoutRoom">确认退房</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <p class="mb-0" id="checkoutRoomMessage">确定要办理退房吗？退房后房间将变为空置状态。</p>
                </div>
                <div class="modal-footer p-1">
                    <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-sm btn-danger" id="confirmCheckoutRoomBtn">确定</button>
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript">
    // 保存楼栋数据的全局变量
    var buildingsData = {};

    // 保存房间数据的全局变量
    var roomsData = {};

    $(function () {
        loadBuildingList();
        
        // 绑定保存按钮点击事件
        $("#saveEditBuildingBtn").on('click', saveEditBuilding);
        $("#saveEditRoomBtn").on('click', saveEditRoom);
        $("#saveAddContractBtn").on('click', saveAddContract);
        
        // 绑定确认删除按钮点击事件
        $("#confirmDeleteBuildingBtn").on('click', confirmDeleteBuilding);
        $("#confirmDeleteRoomBtn").on('click', confirmDeleteRoom);
        $("#confirmCheckoutRoomBtn").on('click', confirmCheckoutRoom);
    });

    function loadBuildingList() {
        $.ajax({
            url: '/api/building/list',
            contentType:'application/json;charset=utf-8',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {
                    $("#err-body").text(res.message);
                    $("#errModal").modal('show');
                    return;
                }
                // 保存楼栋数据到全局变量，使用字符串ID作为key避免大整数精度丢失
                buildingsData = {};
                res.data.forEach(function(building) {
                    buildingsData[String(building.id)] = building;
                });
                // 渲染楼栋列表
                renderBuildings(res.data);
            },
            error: function(xhr, status, error) {
                // 检查是否是重定向状态码
                if (xhr.status === 401) {
                    // 手动导航到重定向URL
                    window.location.href = "/page/login.html";
                } else {
                    // 显示错误提示框并输出错误信息
                    $("#err-body").text("系统异常，请求失败" + xhr.status);
                    $("#errModal").modal('show');
                }
            }
        });
    }

    function renderBuildings(buildings) {
        var $accordion = $("#buildingAccordion");
        $accordion.empty();
        
        if (!buildings || buildings.length === 0) {
            return;
        }

        buildings.forEach(function(building, index) {
            var buildingIndex = index + 1;
            var buildingId = building.id;
            var buildingName = building.name || '';
            var buildingAddress = building.address || '';
            var headingId = 'heading' + buildingIndex;
            var collapseId = 'collapse' + buildingIndex;
            var roomAccordionId = 'roomAccordion' + buildingIndex;

            // 创建楼栋卡片
            var buildingHtml = '<div class="card">' +
                '<div class="card-header p-1 fs" id="' + headingId + '">' +
                '<button class="accordion-button collapsed p-1" type="button" data-bs-toggle="collapse" data-bs-target="#' + collapseId + '" aria-expanded="false" aria-controls="' + collapseId + '">' +
                '<span class="fw-bold">' + buildingName + ' &nbsp;&nbsp; <a class="btn btn-sm btn-danger p-0" onclick="editBuilding(\'' + buildingId + '\')">修改</a> <a class="btn btn-sm btn-danger p-0" onclick="deleteBuilding(\'' + buildingId + '\')">删除</a><br><span class="small fw-normal">' + buildingAddress + '</span></span>' +
                '</button>' +
                '</div>' +
                '<div id="' + collapseId + '" class="collapse" aria-labelledby="' + headingId + '" data-parent="#buildingAccordion">' +
                '<div class="accordion-body p-1">' +
                '<div class="accordion" id="' + roomAccordionId + '">' +
                '<div class="text-center p-2">加载中...</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>';

            $accordion.append(buildingHtml);

            // 加载该楼栋的房间列表
            loadRoomList(buildingId, roomAccordionId);
        });
    }

    function loadRoomList(buildingId, roomAccordionId) {
        $.ajax({
            url: '/api/room/list',
            contentType:'application/json;charset=utf-8',
            type: 'GET',
            data: { buildingId: buildingId },
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {
                    $("#" + roomAccordionId).html('<div class="text-center p-2 text-danger">' + res.message + '</div>');
                    return;
                }
                // 保存房间数据到全局变量
                res.data.forEach(function(room) {
                    roomsData[String(room.id)] = room;
                });
                // 渲染房间列表
                renderRooms(res.data, roomAccordionId);
            },
            error: function(xhr, status, error) {
                if (xhr.status === 401) {
                    window.location.href = "/page/login.html";
                } else {
                    $("#" + roomAccordionId).html('<div class="text-center p-2 text-danger">加载房间列表失败: ' + xhr.status + '</div>');
                }
            }
        });
    }

    function renderRooms(rooms, roomAccordionId) {
        var $roomAccordion = $("#" + roomAccordionId);
        $roomAccordion.empty();

        if (!rooms || rooms.length === 0) {
            $roomAccordion.html('<div class="text-center p-2 text-muted">暂无房间</div>');
            return;
        }

        rooms.forEach(function(room, index) {
            var roomId = room.id;
            var roomName = room.name || '';
            var waterNum = room.waterNum || 0;
            var electricNum = room.electricNum || 0;
            var emptyStatus = room.emptyStatus;
            var tenantName = emptyStatus ? '空置' : '待查询';
            
            // 格式化水表和电表显示（显示后5位）
            var waterDisplay = String(waterNum).padStart(5, '0').slice(-5);
            var electricDisplay = String(electricNum).padStart(5, '0').slice(-5);

            var roomHeadingId = 'roomHeading' + roomAccordionId + '-' + (index + 1);
            var roomCollapseId = 'roomCollapse' + roomAccordionId + '-' + (index + 1);
            
            var roomHtml = '<div class="card' + (index > 0 ? ' pt-1' : '') + '">' +
                '<div class="card-header p-1" id="' + roomHeadingId + '">' +
                '<button class="accordion-button collapsed p-1" type="button" data-bs-toggle="collapse" data-bs-target="#' + roomCollapseId + '" aria-expanded="false" aria-controls="' + roomCollapseId + '">' +
                '<span class="small"><span class="fw-bold">' + roomName + '</span>&nbsp;&nbsp;水表:' + waterDisplay + '&nbsp;&nbsp;电表:' + electricDisplay + '&nbsp;&nbsp;' + tenantName + '</span>' +
                '</button>' +
                '</div>' +
                '<div id="' + roomCollapseId + '" class="collapse" aria-labelledby="' + roomHeadingId + '" data-parent="#' + roomAccordionId + '">' +
                '<div class="accordion-body p-1 d-flex justify-content-evenly">' +
                '<button type="button" class="btn btn-sm btn-warning me-1" onclick="deleteRoom(\'' + roomId + '\')">删除</button>' +
                '<button type="button" class="btn btn-sm btn-info me-1" onclick="editRoom(\'' + roomId + '\')">修改</button>' +
                (emptyStatus ? 
                    '<button type="button" class="btn btn-sm btn-success me-1" onclick="addContract(\'' + roomId + '\')">入住</button>' :
                    '<button type="button" class="btn btn-sm btn-success me-1" onclick="viewContract(\'' + roomId + '\')">租约</button>' +
                    '<button type="button" class="btn btn-sm btn-danger me-1" onclick="checkoutRoom(\'' + roomId + '\')">退房</button>'
                ) +
                '<button type="button" class="btn btn-sm btn-primary me-1" onclick="collectRent(\'' + roomId + '\')">收租</button>' +
                '</div>' +
                '</div>' +
                '</div>';

            $roomAccordion.append(roomHtml);
        });
    }

    function editBuilding(buildingId) {
        // 将ID转换为字符串，避免大整数精度丢失
        buildingId = String(buildingId);
        // 获取楼栋数据
        var building = buildingsData[buildingId];
        if (!building) {
            $("#err-body").text("楼栋数据不存在");
            $("#errModal").modal('show');
            return;
        }

        // 填充表单数据
        $("#editBuildingNameInput").val(building.name || '');
        $("#editBuildingAddressInput").val(building.address || '');
        
        // 清空错误提示
        $("#editBuildingNameBlock").html('&nbsp;&nbsp;楼栋简称不能重复，长度10个字符以内。');
        $("#editBuildingAddressBlock").html('&nbsp;&nbsp;楼栋地址,长度30个字符以内。');
        
        // 保存当前编辑的楼栋ID到按钮的data属性
        $("#saveEditBuildingBtn").data('buildingId', buildingId);
        
        // 显示弹窗
        $("#editBuildingModal").modal('show');
    }

    function saveEditBuilding() {
        var buildingId = $("#saveEditBuildingBtn").data('buildingId');
        if (!buildingId) {
            $("#editBuildingNameBlock").text("楼栋ID不存在");
            return;
        }

        var buildingName = $("#editBuildingNameInput").val();
        var buildingAddress = $("#editBuildingAddressInput").val();

        // 验证输入
        if (!buildingName || buildingName.trim().length === 0) {
            $("#editBuildingNameBlock").text("楼栋简称不能为空");
            return;
        }
        if (buildingName.length > 10) {
            $("#editBuildingNameBlock").text("楼栋简称长度不能超过10个字符");
            return;
        }
        if (!buildingAddress || buildingAddress.trim().length === 0) {
            $("#editBuildingAddressBlock").text("楼栋地址不能为空");
            return;
        }
        if (buildingAddress.length > 30) {
            $("#editBuildingAddressBlock").text("楼栋地址长度不能超过30个字符");
            return;
        }

        // 调用接口保存，将字符串ID转换为数字（如果可能）或保持字符串
        // 注意：如果ID太大，转换为数字会丢失精度，所以直接传递字符串，让后端处理
        var idValue = buildingId;
        // 尝试转换为数字，如果转换后值相同则使用数字，否则使用字符串
        var numId = Number(buildingId);
        if (String(numId) === String(buildingId) && numId <= Number.MAX_SAFE_INTEGER) {
            idValue = numId;
        }
        
        $.ajax({
            url: '/api/building/editBuilding',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({
                id: idValue,
                name: buildingName.trim(),
                address: buildingAddress.trim()
            }),
            success: function(res) {
                if (res.code === 1) {
                    $("#editBuildingNameBlock").text(res.message);
                    return;
                }
                // 隐藏弹窗
                $("#editBuildingModal").modal('hide');
                // 重新加载页面数据
                loadBuildingList();
            },
            error: function(xhr, status, error) {
                if (xhr.status === 401) {
                    window.location.href = "/page/login.html";
                } else {
                    $("#editBuildingNameBlock").text("系统异常，请求失败: " + xhr.status);
                }
            }
        });
    }

    function deleteBuilding(buildingId) {
        // 将ID转换为字符串，避免大整数精度丢失
        buildingId = String(buildingId);
        // 获取楼栋数据
        var building = buildingsData[buildingId];
        if (!building) {
            $("#err-body").text("楼栋数据不存在");
            $("#errModal").modal('show');
            return;
        }

        // 设置删除消息
        var buildingName = building.name || '该楼栋';
        $("#deleteBuildingMessage").text("确定要删除楼栋 \"" + buildingName + "\" 吗？删除后无法恢复。");
        
        // 保存当前要删除的楼栋ID到按钮的data属性
        $("#confirmDeleteBuildingBtn").data('buildingId', buildingId);
        
        // 显示确认删除弹窗
        $("#deleteBuildingModal").modal('show');
    }

    function confirmDeleteBuilding() {
        var buildingId = $("#confirmDeleteBuildingBtn").data('buildingId');
        if (!buildingId) {
            $("#err-body").text("楼栋ID不存在");
            $("#errModal").modal('show');
            return;
        }

        // 调用接口删除，将字符串ID转换为数字（如果可能）或保持字符串
        var idValue = buildingId;
        // 尝试转换为数字，如果转换后值相同则使用数字，否则使用字符串
        var numId = Number(buildingId);
        if (String(numId) === String(buildingId) && numId <= Number.MAX_SAFE_INTEGER) {
            idValue = numId;
        }
        
        $.ajax({
            url: '/api/building/delBuilding',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(idValue),
            success: function(res) {
                if (res.code === 1) {
                    $("#err-body").text(res.message);
                    $("#errModal").modal('show');
                    return;
                }
                // 隐藏弹窗
                $("#deleteBuildingModal").modal('hide');
                // 重新加载页面数据
                loadBuildingList();
            },
            error: function(xhr, status, error) {
                if (xhr.status === 401) {
                    window.location.href = "/page/login.html";
                } else {
                    $("#err-body").text("系统异常，请求失败: " + xhr.status);
                    $("#errModal").modal('show');
                }
            }
        });
    }

    function deleteRoom(roomId) {
        roomId = String(roomId);
        var room = roomsData[roomId];
        if (!room) {
            $("#err-body").text("房间数据不存在");
            $("#errModal").modal('show');
            return;
        }

        var roomName = room.name || '该房间';
        $("#deleteRoomMessage").text("确定要删除房间 \"" + roomName + "\" 吗？删除后无法恢复。");
        $("#confirmDeleteRoomBtn").data('roomId', roomId);
        $("#deleteRoomModal").modal('show');
    }

    function confirmDeleteRoom() {
        var roomId = $("#confirmDeleteRoomBtn").data('roomId');
        if (!roomId) {
            $("#err-body").text("房间ID不存在");
            $("#errModal").modal('show');
            return;
        }

        var idValue = roomId;
        var numId = Number(roomId);
        if (String(numId) === String(roomId) && numId <= Number.MAX_SAFE_INTEGER) {
            idValue = numId;
        }

        $.ajax({
            url: '/api/room/delRoom',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(idValue),
            success: function(res) {
                if (res.code === 1) {
                    $("#err-body").text(res.message);
                    $("#errModal").modal('show');
                    return;
                }
                $("#deleteRoomModal").modal('hide');
                loadBuildingList();
            },
            error: function(xhr, status, error) {
                if (xhr.status === 401) {
                    window.location.href = "/page/login.html";
                } else {
                    $("#err-body").text("系统异常，请求失败: " + xhr.status);
                    $("#errModal").modal('show');
                }
            }
        });
    }

    function editRoom(roomId) {
        roomId = String(roomId);
        var room = roomsData[roomId];
        if (!room) {
            $("#err-body").text("房间数据不存在");
            $("#errModal").modal('show');
            return;
        }

        // 填充表单数据
        $("#editRoomNameInput").val(room.name || '');
        $("#editRoomWaterNumInput").val(room.waterNum || 0);
        $("#editRoomElectricNumInput").val(room.electricNum || 0);

        // 清空错误提示
        $("#editRoomNameBlock").html('&nbsp;&nbsp;房间名长度10个字符以内。');
        $("#editRoomWaterNumBlock").html('&nbsp;&nbsp;当前水表读数。');
        $("#editRoomElectricNumBlock").html('&nbsp;&nbsp;当前电表读数。');

        // 保存当前编辑的房间ID和楼栋ID
        $("#saveEditRoomBtn").data('roomId', roomId);
        $("#saveEditRoomBtn").data('buildingId', String(room.buildingId));

        $("#editRoomModal").modal('show');
    }

    function saveEditRoom() {
        var roomId = $("#saveEditRoomBtn").data('roomId');
        var buildingId = $("#saveEditRoomBtn").data('buildingId');
        if (!roomId) {
            $("#editRoomNameBlock").text("房间ID不存在");
            return;
        }

        var roomName = $("#editRoomNameInput").val();
        var waterNum = $("#editRoomWaterNumInput").val();
        var electricNum = $("#editRoomElectricNumInput").val();

        // 验证输入
        if (!roomName || roomName.trim().length === 0) {
            $("#editRoomNameBlock").text("房间名不能为空");
            return;
        }
        if (roomName.length > 10) {
            $("#editRoomNameBlock").text("房间名长度不能超过10个字符");
            return;
        }
        if (!waterNum || waterNum < 0) {
            $("#editRoomWaterNumBlock").text("水表读数不能为空且必须大于等于0");
            return;
        }
        if (!electricNum || electricNum < 0) {
            $("#editRoomElectricNumBlock").text("电表读数不能为空且必须大于等于0");
            return;
        }

        var idValue = roomId;
        var numId = Number(roomId);
        if (String(numId) === String(roomId) && numId <= Number.MAX_SAFE_INTEGER) {
            idValue = numId;
        }

        var buildingIdValue = buildingId;
        var numBuildingId = Number(buildingId);
        if (String(numBuildingId) === String(buildingId) && numBuildingId <= Number.MAX_SAFE_INTEGER) {
            buildingIdValue = numBuildingId;
        }

        $.ajax({
            url: '/api/room/editRoom',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({
                id: idValue,
                buildingId: buildingIdValue,
                name: roomName.trim(),
                waterNum: parseInt(waterNum),
                electricNum: parseInt(electricNum)
            }),
            success: function(res) {
                if (res.code === 1) {
                    $("#editRoomNameBlock").text(res.message);
                    return;
                }
                $("#editRoomModal").modal('hide');
                loadBuildingList();
            },
            error: function(xhr, status, error) {
                if (xhr.status === 401) {
                    window.location.href = "/page/login.html";
                } else {
                    $("#editRoomNameBlock").text("系统异常，请求失败: " + xhr.status);
                }
            }
        });
    }

    function addContract(roomId) {
        roomId = String(roomId);
        var room = roomsData[roomId];
        if (!room) {
            $("#err-body").text("房间数据不存在");
            $("#errModal").modal('show');
            return;
        }

        // 清空表单
        $("#contractStartDateInput").val('');
        $("#contractEndDateInput").val('');
        $("#contractPriceInput").val('');
        $("#contractLesseeInput").val('');
        $("#contractLesseeMobileInput").val('');
        $("#contractLesseeNoInput").val('');
        $("#contractDepositInput").val('');
        $("#contractRemarkInput").val('');
        $("#contractErrorBlock").text('');

        // 设置默认开始日期为今天
        var today = new Date().toISOString().split('T')[0];
        $("#contractStartDateInput").val(today);

        // 保存房间ID
        $("#saveAddContractBtn").data('roomId', roomId);

        $("#addContractModal").modal('show');
    }

    function saveAddContract() {
        var roomId = $("#saveAddContractBtn").data('roomId');
        if (!roomId) {
            $("#contractErrorBlock").text("房间ID不存在");
            return;
        }

        var startDate = $("#contractStartDateInput").val();
        var endDate = $("#contractEndDateInput").val();
        var price = $("#contractPriceInput").val();
        var lessee = $("#contractLesseeInput").val();
        var lesseeMobile = $("#contractLesseeMobileInput").val();
        var lesseeNo = $("#contractLesseeNoInput").val();
        var deposit = $("#contractDepositInput").val();
        var remark = $("#contractRemarkInput").val();

        // 验证输入
        if (!startDate) {
            $("#contractErrorBlock").text("开始日期不能为空");
            return;
        }
        if (!endDate) {
            $("#contractErrorBlock").text("截止日期不能为空");
            return;
        }
        if (new Date(endDate) < new Date(startDate)) {
            $("#contractErrorBlock").text("截止日期不能早于开始日期");
            return;
        }
        if (!price || price < 1) {
            $("#contractErrorBlock").text("每月租金不能为空且必须大于0");
            return;
        }
        if (!lessee || lessee.trim().length === 0) {
            $("#contractErrorBlock").text("承租人姓名不能为空");
            return;
        }
        if (lessee.length > 30) {
            $("#contractErrorBlock").text("承租人姓名长度不能超过30个字符");
            return;
        }
        if (!lesseeMobile || !/^1[3-9]\d{9}$/.test(lesseeMobile)) {
            $("#contractErrorBlock").text("手机号格式不正确");
            return;
        }
        if (!lesseeNo || !/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/.test(lesseeNo)) {
            $("#contractErrorBlock").text("身份证号格式不正确");
            return;
        }
        if (!deposit || deposit < 0) {
            $("#contractErrorBlock").text("押金不能为空且必须大于等于0");
            return;
        }
        if (remark && remark.length > 60) {
            $("#contractErrorBlock").text("备注长度不能超过60个字符");
            return;
        }

        var idValue = roomId;
        var numId = Number(roomId);
        if (String(numId) === String(roomId) && numId <= Number.MAX_SAFE_INTEGER) {
            idValue = numId;
        }

        $.ajax({
            url: '/api/contract/add',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({
                roomId: idValue,
                startDate: startDate,
                endDate: endDate,
                price: parseInt(price),
                lessee: lessee.trim(),
                lesseeMobile: lesseeMobile.trim(),
                lesseeNo: lesseeNo.trim().toUpperCase(),
                deposit: parseInt(deposit),
                remark: remark ? remark.trim() : ''
            }),
            success: function(res) {
                if (res.code === 1) {
                    $("#contractErrorBlock").text(res.message);
                    return;
                }
                $("#addContractModal").modal('hide');
                loadBuildingList();
            },
            error: function(xhr, status, error) {
                if (xhr.status === 401) {
                    window.location.href = "/page/login.html";
                } else {
                    var errorMsg = "系统异常，请求失败";
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                    $("#contractErrorBlock").text(errorMsg);
                }
            }
        });
    }

    function viewContract(roomId) {
        roomId = String(roomId);
        var idValue = roomId;
        var numId = Number(roomId);
        if (String(numId) === String(roomId) && numId <= Number.MAX_SAFE_INTEGER) {
            idValue = numId;
        }

        $.ajax({
            url: '/api/contract/find-by-room-id',
            contentType:'application/json;charset=utf-8',
            type: 'GET',
            data: { roomId: idValue },
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {
                    $("#err-body").text(res.message);
                    $("#errModal").modal('show');
                    return;
                }
                var contract = res.data;
                if (!contract) {
                    $("#err-body").text("未找到有效合同");
                    $("#errModal").modal('show');
                    return;
                }

                // 填充合同信息
                $("#viewContractStartDate").text(contract.startDate || '');
                $("#viewContractEndDate").text(contract.endDate || '');
                $("#viewContractPrice").text(contract.price ? contract.price + ' 元' : '');
                $("#viewContractLessee").text(contract.lessee || '');
                $("#viewContractLesseeMobile").text(contract.lesseeMobile || '');
                $("#viewContractLesseeNo").text(contract.lesseeNo || '');
                $("#viewContractDeposit").text(contract.deposit ? contract.deposit + ' 元' : '');
                $("#viewContractRemark").text(contract.remark || '');

                $("#viewContractModal").modal('show');
            },
            error: function(xhr, status, error) {
                if (xhr.status === 401) {
                    window.location.href = "/page/login.html";
                } else {
                    $("#err-body").text("系统异常，请求失败: " + xhr.status);
                    $("#errModal").modal('show');
                }
            }
        });
    }

    function checkoutRoom(roomId) {
        roomId = String(roomId);
        var room = roomsData[roomId];
        if (!room) {
            $("#err-body").text("房间数据不存在");
            $("#errModal").modal('show');
            return;
        }

        var roomName = room.name || '该房间';
        $("#checkoutRoomMessage").text("确定要办理房间 \"" + roomName + "\" 的退房吗？退房后房间将变为空置状态。");
        $("#confirmCheckoutRoomBtn").data('roomId', roomId);
        $("#checkoutRoomModal").modal('show');
    }

    function confirmCheckoutRoom() {
        var roomId = $("#confirmCheckoutRoomBtn").data('roomId');
        if (!roomId) {
            $("#err-body").text("房间ID不存在");
            $("#errModal").modal('show');
            return;
        }

        var idValue = roomId;
        var numId = Number(roomId);
        if (String(numId) === String(roomId) && numId <= Number.MAX_SAFE_INTEGER) {
            idValue = numId;
        }

        $.ajax({
            url: '/api/contract/checkout',
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(idValue),
            success: function(res) {
                if (res.code === 1) {
                    $("#err-body").text(res.message);
                    $("#errModal").modal('show');
                    return;
                }
                $("#checkoutRoomModal").modal('hide');
                loadBuildingList();
            },
            error: function(xhr, status, error) {
                if (xhr.status === 401) {
                    window.location.href = "/page/login.html";
                } else {
                    var errorMsg = "系统异常，请求失败";
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                    $("#err-body").text(errorMsg);
                    $("#errModal").modal('show');
                }
            }
        });
    }

    function collectRent(roomId) {
        console.log('收租:', roomId);
        // TODO: 实现收租功能（此功能可能需要单独的页面或弹窗）
        $("#err-body").text("收租功能待实现");
        $("#errModal").modal('show');
    }
</script>
</html>
